<style>
.ivu-table th {
  background-color: #fff !important;
}
</style>
<template>
  <div>
    <div class="ivu-mt">
      <el-card :bordered="false">
        <p class="card-title">
          {{$t('message.term.word_search')}}
        </p>
        <el-divider dashed />
        <form-create ref="fc" v-model="fApi" :rule="rule" :option="option" @ld-on-change="onFormCreateChange"></form-create>
        <el-divider dashed />
        <div>
          <el-button type="info" @click="search()">{{$t('message.button.select_files')}}</el-button>
        </div>
      </el-card>
    </div>
    <div class="ivu-mt">
      <el-card :bordered="false">
        <p class="card-title">
          {{$t('message.notice.have_chosen')}} : {{countDocSelected()}}
        </p>
        <el-divider dashed />
        <!-- Table :columns="columnsDefinition" :data="dataList" @on-selection-change="onDocSelectChange"></Table -->
        <StretchTable :columns="columnsDefinition" :stretchColums="stretchColums" :data="dataList" @on-selection-change="onDocSelectChange"></StretchTable>
        <div style="text-align: right;  margin-top: 20px">
          <el-button type="success" @click="nextStep()">下一步</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { API } from '@/customized/http/api';
import StretchTable from '@/components/stretch-table/stretch-table.vue'
export default {
  /*从父路由注入父路由页面的函数*/
  inject: ['next', 'back'],
  components: {
    formCreate: formCreate.$form(),
    StretchTable
  },
  data() {
    return {
      fApi: {},
      model: {},
      //表单生成规则
      rule: [],
      //组件参数配置
      option: {
        submitBtn: false,
        resetBtn: false
      },
      isCollapsed: false,
      loginModal: false,
      columnsDefinition: [{
        type: 'selection',
        width: 60,
        align: 'center'
      },
        {
          title: '文件名',
          key: 'name',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '价格(元)',
          width: 120,
          key: 'price',
          align: 'right'
        },
        /*{
            title: '优惠',
            width: 120,
            key: 'discountName'
        },*/
        {
          title: '优惠后价格',
          width: 120,
          key: 'finalPrice',
          align: 'right'
        }
      ],
      stretchColums: ['price'],
      dataList: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  watch: {
    /*$route(to) {
      this.init();
    }*/
  },
  computed: {
    dataSelected: {
      get() {
        /*注意getters的用法*/
        return this.$store.getters.docSelected;
      },
      set(val) {
        this.$store.commit('saveDocSelected', val);
      }
    }
  },
  methods: {
    init() {
      this.loadTagRules(this.$route.params.docType);
      this.dataList = [];
    },
    nextStep() {
      if (!this.dataSelected || this.dataSelected.length === 0) {
        this.$Notice.warning({
          title: this.$t('message.notice.warning'),
          desc: this.$t('message.notice.please_pick_some_documents')
        });
        return;
      }
      this.next(this.$route.name);
    },
    searchWord(tagIds) {
      if (!tagIds || tagIds.length === 0) {
        this.$Notice.warning({
          title: this.$t('message.notice.warning'),
          desc: this.$t('message.notice.please_pick_enough_tags')
        });
        return;
      }

      let exist = tagIds.some(it => {
        return it === "";
      });
      if(exist) {
        this.$Notice.warning({
          title: this.$t('message.notice.warning'),
          desc: this.$t('message.notice.please_pick_enough_tags')
        });
        return;
      }

      /*{"tags":[1,4,12]}*/
      let postJson = {};
      postJson.tags = tagIds;
      API.searchWord({ formData: JSON.stringify(postJson) })
          .then((res) => {
            this.dataList = res.data;
            let newDataSelected = [];
            if (!!this.dataSelected) {
              this.dataList.map(item => {
                let exist = this.dataSelected.some(it => {
                  return it.id === item.id;
                })

                if (exist) {
                  item._checked = true;
                  newDataSelected.push(item); // 更新dataSelected中的数据，比如价格已经变化了
                } else {
                  delete item._checked;
                }
              })
              this.dataSelected = newDataSelected;
            }
          }).catch((error) => {
        console.log(error);
      });
    },
    /*勾选了哪些文件*/
    onDocSelectChange(selection) {
      this.dataSelected = selection;
    },
    /*勾选了的文件数量*/
    countDocSelected() {
      return this.dataSelected.length;
    },
    search() {
      let tagIdArray = this.fApiFormData();
      this.searchWord(tagIdArray);
    },
    loadTagRules(docType) {
      API.loadTagRules({
        domain: docType
      }).then((res) => {
        if (!!res) {
          let rules = res.data;
          if (rules) {
            this.rule = rules;
          }
        }
      }).catch((error) => {
        console.log(error);
      });
    },
    fApiFormData() {
      let result = [];
      let fields = this.fApi.fields();
      fields.forEach((item) => {//,index
        let kv = {
          key: item,
          value: this.fApi.getValue(item)
        };
        result.push(kv);
      });
      //let result = this.fApi.formData(); 遇到checkbox会出问题，返回的不是value

      let tagIdArray = [];
      result.forEach((item) => {//,index
        if (item.value instanceof Array) {
          item.value.forEach((tagId) => {//,index
            tagIdArray.push(tagId);
          });
        } else {
          tagIdArray.push(item.value);
        }
      });
      return tagIdArray;
    },
    onFormCreateChange(inject, val) {
      if (inject.inject.docType === 'stock-company-non-lawsuit') {
        this.repel(inject, val, "临时股东大会", "年度股东大会");
        this.repel(inject, val, "年度股东大会", "临时股东大会")
      }
    },
    repel(inject, val, option1, option2) {
      let annualIndex = val.findIndex(item => item === option1);
      let options = inject.rule[0].options;
      let index = options.findIndex(item => item.label === option2);

      if (annualIndex !== -1) {
        let excludeIndex = val.findIndex(item => item === option2);
        if (excludeIndex !== -1) {
          val.splice(excludeIndex, 1);
        }

        options[index].disabled = true;
      } else {
        delete options[index].disabled;
      }

      let realValue = [];
      val.forEach((item1) => {//index
        options.forEach((item2) => {//,index
          if (item2.label === item1) {
            realValue.push(item2.value);
          }
        })
      });

      inject.$f.setValue(inject.rule[0].field, realValue);
      inject.$f.refresh(true);
    }
  }
}
</script>